<?php
/**
 * 消息管理类.
 * User: chan
 * Date: 2017/8/16 19:03
 */
namespace WeChat;
class News
{
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        file_put_contents('aaa.txt',$postStr);
        if(empty($postStr)){
            ob_clean();
            exit("");
        }
        $postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
        $RX_TYPE = trim($postObj->MsgType);
        switch( $RX_TYPE ){
            case 'text':
                $resultStr = $this->receiveText($postObj);
                break;
            case "event":
                $resultStr = $this->receiveEvent($postObj);
                break;
            default:
                $resultStr='';
                break;
        }
        ob_clean();
        echo $resultStr;
        exit("");
    }
    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        switch($keyword){
            case "你好":
                $contentStr ='您好，欢迎关注我们';
                break;
            default:
                $contentStr = "系统暂时无法识别该指令！";
                break;
        }
        $resultStr = $this->replyText($object, $contentStr);
        return $resultStr;
    }
    //接收用户事件，关注等
    private function receiveEvent($object)
    {
        switch ($object->Event)
        {
            case "subscribe":
                $contentStr = "欢迎关注我们";
                break;
            case "unsubscribe":
                $contentStr = "感谢你的使用，欢迎下次回来！";
                break;
            case "CLICK":
                break;
            default:
                break;
        }
        $resultStr = $this->replyText($object,$contentStr);
        return $resultStr;
    }
    //回复文本消息
    private function replyText($object, $content)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $resultStr;
    }
}